<template>
  <div class="section">
    <h2>Excel 导出</h2>
    <div class="export-controls">
      <button 
        @click="exportExcel"
        :disabled="!data || data.length === 0"
      >
        导出数据
      </button>
      <div v-if="message" :class="{'success': success, 'error': !success}">
        {{ message }}
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  props: {
    data: {
      type: Array,
      default: () => []
    },
    columns: {
      type: Array,
      default: () => []
    },
    filename: {
      type: String,
      default: '导出数据.xlsx'
    },
    sheetName: {
      type: String,
      default: 'Sheet1'
    }
  },
  data() {
    return {
      message: '',
      success: false
    };
  },
  methods: {
    exportExcel() {
      if (!this.data || this.data.length === 0) {
        this.message = '没有数据可导出';
        this.success = false;
        return;
      }
      
      try {
        // 构建导出数据
        const exportData = this.data.map(row => {
          const newRow = {};
          this.columns.forEach(col => {
            newRow[col.label] = row[col.prop];
          });
          return newRow;
        });
        
        // 创建工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData);
        
        // 创建工作簿并添加工作表
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, this.sheetName);
        
        // 生成 Excel 文件并下载
        XLSX.writeFile(workbook, this.filename);
        
        this.message = `成功导出 ${this.data.length} 条数据`;
        this.success = true;
      } catch (error) {
        this.message = '导出失败，请重试';
        this.success = false;
        console.error('导出 Excel 失败:', error);
      }
    }
  }
};
</script>
